<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">

      <el-form-item label="姓名" prop="name">
        <el-input v-model="queryParams.name" placeholder="请输入姓名" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>

      <el-form-item label="联系电话" prop="phone">
        <el-input v-model="queryParams.phone" placeholder="请输入联系电话" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>

      <el-form-item label="真实客户" prop="authentic">
        <el-select v-model="queryParams.authentic" placeholder="请选择是否为真实客户" style="width: 100%">
          <el-option v-for="dict in dict.type.sys_is_0_1" :key="dict.value" :label="dict.label"
            :value="dict.value"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['demo:customer:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['demo:customer:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['demo:customer:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['demo:customer:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="customerList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="所属门店" align="center" prop="deptName" width="150" />

      <el-table-column label="微信头像" align="center" prop="avatar" width="80">
        <template slot-scope="scope">
          <img v-if="scope.row.avatar" :src="scope.row.avatar" style="width: 40px; height: 40px; border-radius: 50%;" />
        </template>
      </el-table-column>
      <el-table-column label="微信昵称" align="center" prop="nickName" width="150" />
      <el-table-column label="姓名" align="center" prop="name" />
      <el-table-column label="年龄" align="center" prop="age" />
      <el-table-column label="性别" align="center" prop="sex">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_user_sex" :value="scope.row.sex" />
        </template>
      </el-table-column>
      <el-table-column label="身高（CM）" align="center" prop="height" />
      <el-table-column label="体重（KG）" align="center" prop="weight" />
      <el-table-column label="联系电话" align="center" prop="phone" />
      <!-- <el-table-column label="微信唯一id" align="center" prop="openId" /> -->
      <!-- <el-table-column label="客户画像" align="center" prop="portrait" /> -->
      <el-table-column label="客户附加信息" align="center" prop="remark" width="300" />
      <el-table-column label="是否真实客户" align="center" prop="authentic">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_is_0_1" :value="scope.row.authentic" />
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="240">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="toApp(scope.row)"
            v-hasPermi="['demo:customer:edit']">去模拟</el-button>

          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['demo:customer:edit']">修改</el-button>

          <el-button size="mini" type="text" icon="el-icon-picture-outline" @click="handleInfo(scope.row)"
            v-hasPermi="['demo:customer:edit']">查看</el-button>
          <!-- <el-button size="mini" type="text" icon="el-icon-picture-outline" @click="handlePortrait(scope.row)"
            v-hasPermi="['demo:customer:edit']">生成画像</el-button> -->
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['demo:customer:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改顾客信息抽屉 -->
    <el-drawer :title="title" :visible.sync="formDrawerVisible" direction="rtl" size="50%" append-to-body
      class="customer-form-drawer">
      <div class="drawer-content">
        <div class="flex mb20" style="justify-content: start; align-items: center;">

          <img :src="form.avatar" alt="" style="width:60px; height: 60px; border-radius: 50%;" class="mr20"
            v-if="form.avatar" />
          <!-- 描述表格 -->
          <el-descriptions style="width:calc(100% - 80px);" class="" title="" direction="vertical" :column="2" border>
            <el-descriptions-item label="微信昵称">{{ form.nickName }}</el-descriptions-item>
            <el-descriptions-item label="所属门店">{{ form.deptName }}</el-descriptions-item>
          </el-descriptions>
        </div>
        <el-form ref="form" :model="form" :rules="rules" label-width="80px">


          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="姓名" prop="name">
                <el-input v-model="form.name" placeholder="请输入姓名" />
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="年龄" prop="age">
                <el-input v-model="form.age" placeholder="请输入年龄" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="性别" prop="sex">
                <el-select v-model="form.sex" placeholder="请选择性别" style="width: 100%">
                  <el-option v-for="dict in dict.type.sys_user_sex" :key="dict.value" :label="dict.label"
                    :value="dict.value"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="联系电话" prop="phone">
                <el-input v-model="form.phone" placeholder="请输入联系电话" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="身高" prop="height">
                <el-input v-model="form.height" placeholder="请输入身高(CM)" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="体重" prop="weight">
                <el-input v-model="form.weight" placeholder="请输入体重(KG)" />
              </el-form-item>
            </el-col>

            <el-col :span="24">
              <el-form-item label="真实客户" prop="authentic">
                <el-select v-model="form.authentic" placeholder="请选择是否为真实客户" style="width: 100%">
                  <el-option v-for="dict in dict.type.sys_is_0_1" :key="dict.value" :label="dict.label"
                    :value="dict.value"></el-option>
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :span="24">
              <el-form-item label="附加信息" prop="remark">
                <el-input v-model="form.remark" type="textarea" rows="10" placeholder="请输入附加信息（生成画像时必填）" />
              </el-form-item>
            </el-col>



            <!-- <el-col :span="24" v-if="form.authentic == 0">
              <el-form-item label="微信标识" prop="openId">
                <el-input v-model="form.openId" placeholder="微信扫码填入openID" />
              </el-form-item>
            </el-col> -->

            <el-col :span="24" v-if="form.authentic == 0">
              <el-form-item label="微信昵称" prop="nickName">
                <el-input v-model="form.nickName" placeholder="请输入虚拟微信昵称" />
              </el-form-item>
            </el-col>

            <el-col :span="24" v-if="form.authentic == 0">
              <el-form-item label="微信头像" prop="avatar">
                <image-upload v-model="form.avatar" :limit="1" />
              </el-form-item>
            </el-col>

          </el-row>
        </el-form>
      </div>
      <div class="drawer-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-drawer>

    <!-- 客户详情抽屉 -->
    <el-drawer :title="drawerTitle" :visible.sync="drawerVisible" direction="rtl" size="50%" append-to-body>
      <div class="p20 customer-detail-drawer">
        <el-descriptions class="margin-top" :column="2" border>
          <el-descriptions-item label="姓名">{{ drawerData.name }}</el-descriptions-item>
          <el-descriptions-item label="年龄">{{ drawerData.age }}</el-descriptions-item>
          <el-descriptions-item label="性别">
            <dict-tag :options="dict.type.sys_user_sex" :value="drawerData.sex" />
          </el-descriptions-item>
          <el-descriptions-item label="身高">{{ drawerData.height }} CM</el-descriptions-item>
          <el-descriptions-item label="体重">{{ drawerData.weight }} KG</el-descriptions-item>
          <el-descriptions-item label="联系电话">{{ drawerData.phone }}</el-descriptions-item>
          <el-descriptions-item label="微信标识">{{ drawerData.openId }}</el-descriptions-item>
          <el-descriptions-item label="附加信息">{{ drawerData.remark }}</el-descriptions-item>
        </el-descriptions>

        <!-- <el-descriptions-item label="客户画像">{{ drawerData.portrait }}</el-descriptions-item> -->
        <!-- 这里展示msgData的内容 -->
        <div v-if="drawerData.preliminaryProposalJson" class="proposal-container">
          <div class="grid grid-cols-1 md:grid-cols-2 gap-4 mt-4">
            <div
              class="msg-data-section mb-4 p-4 bg-white rounded-xl shadow-sm border border-gray-200 transition-all hover:shadow-md"
              v-for="(items, category) in drawerData.preliminaryProposalJson" :key="category"
              v-if="category == '人生阶段' || category == '体重指数'">
              <h3
                class="section-title text-primary font-semibold text-lg mb-3 pb-2 border-b border-secondary border-opacity-30 flex items-center">
                <i class="el-icon-user-solid mr-2 text-pink-500 text-xl"></i>
                <span>{{ category }} | {{ items }}</span>
              </h3>
            </div>
            <div
              class="msg-data-section mb-4 p-4 bg-white rounded-xl shadow-sm border border-gray-200 transition-all hover:shadow-md"
              v-for="(items, category) in drawerData.preliminaryProposalJson" :key="category"
              v-if="category != '人生阶段' && category != '体重指数'">
              <h3
                class="section-title text-primary font-semibold text-lg mb-3 pb-2 border-b border-secondary border-opacity-30 flex items-center">
                <i class="el-icon-star-off mr-2 text-yellow-500 text-xl"
                  v-if="category.includes('建议') || category.includes('推荐')"></i>
                <i class="el-icon-lollipop mr-2 text-red-400 text-xl" v-else-if="category.includes('饮食')"></i>
                <i class="el-icon-folder-checked mr-2 text-blue-500 text-xl" v-else-if="category.includes('习惯')"></i>
                <i class="el-icon-bicycle mr-2 text-green-500 text-xl" v-else-if="category.includes('运动')"></i>
                <i class="el-icon-moon-night mr-2 text-indigo-400 text-xl" v-else-if="category.includes('护肤')"></i>
                <i class="el-icon-menu mr-2 text-purple-500 text-xl" v-else></i>
                <span>{{ category }}</span>
              </h3>
              <ul class="section-list space-y-2">
                <li v-for="(item, index) in items" :key="index"
                  class="list-item flex items-start p-2 hover:bg-gray-50 rounded-lg text-base">
                  <i class="el-icon-arrow-right text-primary mr-2 mt-1 text-sm"></i>
                  <span class="text-gray-700">{{ item }}</span>
                </li>
              </ul>
            </div>
          </div>
        </div>
      </div>
    </el-drawer>
  </div>
</template>

<script>
import { listCustomer, getCustomerByOpenId, getCustomer, delCustomer, addCustomer, updateCustomer } from "@/api/demo/customer";
import { generatePortrait } from "@/api/demo/deepseek";

export default {
  name: "Customer",
  dicts: ['sys_user_sex', 'sys_is_0_1'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 顾客信息表格数据
      customerList: [],
      // 弹出层标题
      title: "",
      // 是否显示表单抽屉
      formDrawerVisible: false,
      // 抽屉是否显示
      drawerVisible: false,
      // 抽屉标题
      drawerTitle: "客户详情",
      // 抽屉数据
      drawerData: {},
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        deptId: null,
        name: null,
        age: null,
        sex: null,
        height: null,
        weight: null,
        phone: null,
        openId: null,
        portrait: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        openId: [
          { required: true, message: "微信唯一id不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询顾客信息列表 */
    getList() {
      this.loading = true;
      listCustomer(this.queryParams).then(response => {
        this.customerList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.formDrawerVisible = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        deptId: null,
        name: null,
        age: null,
        sex: "1",
        height: null,
        weight: null,
        phone: null,
        openId: null,
        portrait: null,
        authentic: "1",
        remark: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.formDrawerVisible = true;
      this.title = "添加顾客信息";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getCustomer(id).then(response => {
        this.form = response.data;
        this.formDrawerVisible = true;
        this.title = "修改顾客信息";
      });
    },
    /** 查看详情按钮操作 */
    handleInfo(row) {
      row.proposalJson = row.proposalJson ? JSON.parse(row.proposalJson) : {};
      row.preliminaryProposalJson = row.preliminaryProposal ? JSON.parse(row.preliminaryProposal) : {};
      this.drawerData = { ...row };
      this.drawerTitle = "客户详情 - " + (row.name || "");
      this.drawerVisible = true;
    },

    handlePortrait(row) {
      if (!row || !row.id) {
        this.$modal.msgError("请选择顾客");
        return false
      }
      if (!row.remark || row.remark.length <= 1) {
        this.$modal.msgError("请先填写需要备注的信息，以便更好的生成画像");
        return false
      }
      this.loading = true;

      generatePortrait({ openId: row.openId }).then(response => {
        if (response.code == 200) {
          this.$modal.msgSuccess("画像生成成功");
          this.getList();
          this.loading = false;

        }
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateCustomer(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.formDrawerVisible = false;
              this.getList();
            });
          } else {
            addCustomer(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.formDrawerVisible = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除顾客信息编号为"' + ids + '"的数据项？').then(function () {
        return delCustomer(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('demo/customer/export', {
        ...this.queryParams
      }, `customer_${new Date().getTime()}.xlsx`)
    },
    toApp(row) {
      if (!row || !row.openId) {
        this.$modal.msgError("该客户无微信标识，无法模拟登录");
        return false
      }
      localStorage.setItem('openId', row.openId)
      localStorage.setItem('deptId', row.deptId)
      localStorage.setItem('CustomerInfo', JSON.stringify(row))

      this.$router.push({ path: '/app' });
    }
  }
};
</script>

<style scoped>
.proposal-container {
  margin-top: 20px;
}

.section-title {
  font-weight: 600;
}

.section-list {
  padding-left: 10px;
}

/* 表单抽屉样式 */
.customer-form-drawer {
  /* 自定义样式 */
}

.drawer-content {
  padding: 20px;
  height: calc(100% - 70px);
  overflow-y: auto;
}

.drawer-footer {
  position: absolute;
  bottom: 0;
  width: 100%;
  border-top: 1px solid #e8e8e8;
  padding: 10px 16px;
  text-align: right;
  background: #fff;
  z-index: 1;
}
</style>